$(function () {
    var queryUrl = '../sparepart/list';
    var Id = getQueryString('Id');
    if (Id) {
        queryUrl += '?Id=' + Id
        vm.q.status = 0;
        vm.isFromApprove = true;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        rownumWidth: 50,
        colModel: [
            {label: '备件编码', name: 'partCode', index: 'PART_CODE', width: 50},
            {label: 'ERP编码', name: 'erpCode', index: 'ERP_CODE', width: 55},
            {label: '名称', name: 'name', index: 'NAME', width: 75},
            {label: '规格', name: 'spec', index: 'SPEC'},
            {label: '价格', name: 'price', index: 'UNIT', width: 40},
            {label: '安全', name: 'safeNum', index: 'SAFE_NUM', width: 30},
            {
                label: '库存', name: 'stockNum', index: 'STOCK_NUM', width: 30,
                formatter: function (value, options, row) {
                    if (row.stockNum < row.safeNum) {
                        return '<a style="color: red">' + row.stockNum + '</a>';
                    } else {
                        return value;
                    }
                }
            },
            {label: '在途', name: 'transitNum', index: 'TRANSIT_NUM', width: 30},
            {label: '制造商', name: 'producor', index: 'PRODUCOR', width: 85},
            {label: '录入人', name: 'createUserName', index: 'CREATE_USER', width: 35},
            {
                label: '是否有效', name: 'isValid', width: 36, align: 'center', formatter: function (value) {
                    return value === 0 ?
                        '<span class="label label-danger">失效</span>' :
                        '<span class="label label-success">正常</span>';
                }
            },
            {

                label: '状态', width: 50, align: 'center',
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>" + sysEnums.CHECK_FLAG[row.status] + "</button>";
                },
                cellattr: function (value, options, row) {
                    if (row.status == 1) {
                        return '';
                    } else {
                        return "style='background-color: #d2cece;'";
                    }
                    ;
                }
            },
            {label: '', name: 'status', index: 'STATUS', width: 80, hidden: true},
            {label: 'ABC类', name: 'planAbc', index: 'PLAN_ABC', width: 80, hidden: true},
            {name: 'id', key: true, hidden: true},
            {name: 'reserve3', hidden: true},
            {
                label: '设备', width: 30, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    var type = row.type;
                    if (type == 1) {
                        return "<button class='btn btn-outline btn-info' onclick='vm.addDev(\"" + row.id + "\",\"" + row.producor + "\",\"" + row.devType + "\")'><i class='fa fa-plus-circle'></i></button>";
                    } else {
                        return "暂无";
                    }
                }
            },
            {
                label: '替换', width: 30, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' onclick='vm.addReplace(\"" + row.id + "\",\"" + row.producor + "\",\"" + row.devType + "\")'><i class='fa fa-plus-circle'></i></button>";
                }
            },
            {
                label: '台账', width: 30, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' onclick='vm.reportDetail(\"" + row.id + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            }
        ],
        postData: {
            'status': vm.q.status
        }
    });
    vm.getRoleList();
    vm.getSparePartUnit();
    vm.loadSparePartInstallPosition();

});
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "typeCode",
            pIdKey: "typePid",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        }
    },
    callback: {
        beforeCheck: true,
    }
};

var vm = new Vue({
    el: '#rrapp',
    data() {
        const validateExistsCheckErp = (rule, value, callback) => {
            if (!this.sparePart.id) {
                if (this.sparePart.erpCode && this.sparePart.erpCode.trim()) {
                    this.sparePart.erpCode = this.sparePart.erpCode.trim();
                    Ajax.request({
                        url: '../sparepart/isExists',
                        params: {
                            'erpCode': this.sparePart.erpCode,
                        },
                        type: "POST",
                        async: true,
                        successCallback: function (r) {
                            if (r.rows) {
                                callback(new Error('存在' + r.rows + '与新增的erp相同，请确认！'));
                            } else {
                                // validateDisabled 是否校验
                                // validateState 展示状态（校验错误时此处值为 'error'）
                                // validateMessage 错误提示文字
                                let idx = (rule.field == 'name') ? 1 : 0;
                                // 清空另外项的异常状态
                                vm.$refs.formValidate.fields[idx].validateState = '';
                                vm.$refs.formValidate.fields[idx].validateMessage = '';
                                callback();
                            }
                        }
                    })
                } else {
                    callback();
                }
            } else {
                if (this.sparePart.erpCode && this.sparePart.erpCode.trim()) {
                    this.sparePart.erpCode = this.sparePart.erpCode.trim();
                    Ajax.request({
                        url: '../sparepart/isExists',
                        params: {
                            'id': this.sparePart.id,
                            'erpCode': this.sparePart.erpCode,
                        },
                        type: "POST",
                        async: true,
                        successCallback: function (r) {
                            if (r.rows) {
                                callback(new Error('存在' + r.rows + '与编辑的erp相同，请确认！'));
                            } else {
                                // validateDisabled 是否校验
                                // validateState 展示状态（校验错误时此处值为 'error'）
                                // validateMessage 错误提示文字
                                let idx = (rule.field == 'name') ? 1 : 0;
                                // 清空另外项的异常状态
                                vm.$refs.formValidate.fields[idx].validateState = '';
                                vm.$refs.formValidate.fields[idx].validateMessage = '';
                                callback();
                            }
                        }
                    })
                } else {
                    callback();
                }
            }
        };
        const validateExistsCheck = (rule, value, callback) => {
            if (value == '') {
                if (rule.field == 'name') {
                    callback(new Error('备件名称必填！'));
                } else if (rule.field == 'spec') {
                    callback(new Error('备件规格必填！'));
                }
            } else {
                if (!this.sparePart.id) {
                    if (this.sparePart.name && this.sparePart.spec) {
                        // 校验备件名称+规格是否存在
                        Ajax.request({
                            url: '../sparepart/isExists',
                            params: {
                                'name': this.sparePart.name,
                                'spec': this.sparePart.spec
                            },
                            type: "POST",
                            async: true,
                            successCallback: function (r) {
                                if (r.rows) {
                                    callback(new Error('存在 ' + r.rows + '与新增备件名称和规格一样，请确认！'));
                                } else {
                                    // validateDisabled 是否校验
                                    // validateState 展示状态（校验错误时此处值为 'error'）
                                    // validateMessage 错误提示文字
                                    let idx = (rule.field == 'name') ? 1 : 0;
                                    // 清空另外项的异常状态
                                    vm.$refs.formValidate.fields[idx].validateState = '';
                                    vm.$refs.formValidate.fields[idx].validateMessage = '';
                                    callback();
                                }
                            }
                        });
                    } else {
                        callback();
                    }
                } else {
                    if (this.sparePart.name && this.sparePart.spec) {
                        // 校验备件名称+规格是否存在
                        Ajax.request({
                            url: '../sparepart/isExists',
                            params: {
                                'id': this.sparePart.id,
                                'name': this.sparePart.name,
                                'spec': this.sparePart.spec
                            },
                            type: "POST",
                            async: true,
                            successCallback: function (r) {
                                if (r.rows) {
                                    callback(new Error('存在 ' + r.rows + '与新增备件名称和规格一样，请确认！'));
                                } else {
                                    // validateDisabled 是否校验
                                    // validateState 展示状态（校验错误时此处值为 'error'）
                                    // validateMessage 错误提示文字
                                    let idx = (rule.field == 'name') ? 1 : 0;
                                    // 清空另外项的异常状态
                                    vm.$refs.formValidate.fields[idx].validateState = '';
                                    vm.$refs.formValidate.fields[idx].validateMessage = '';
                                    callback();
                                }
                            }
                        });
                    } else {
                        callback();
                    }
                }
            }
        };
        return {
            isEditable: true, // 是否可编辑
            isFromApprove: false, // 是通过审核菜单过来的，需要隐藏
            isPrivilege: 0, // 是否是特权
            showList: true,
            title: null,
            sparePart: {
                name: '',
                spec: '',
                price: '',
                unit: '',
                planAbc: ''
            },
            ruleValidate: {
                name: [
                    {required: true, message: '备件名称必填！', trigger: 'change'},
                    {validator: validateExistsCheck, trigger: 'blur'},
                    {
                        required: true,
                        pattern: /^[^\s（）φ]*$/,
                        message: '不能输入空格，中文括号，小写直径',
                        trigger: 'blur'
                    }
                ],
                spec: [
                    {required: true, message: '规格必填！', trigger: 'change'},
                    {validator: validateExistsCheck, trigger: 'blur'},
                    {
                        required: true,
                        pattern: /^[^\s（）φ]*$/,
                        message: '不能输入空格，中文括号，小写直径',
                        trigger: 'blur'
                    }
                ],
                erpCode: [
                    {validator: validateExistsCheckErp, trigger: 'blur'},
                ],
                producerCode: [
                    {required: true, message: '制造商必填！', trigger: 'change'}
                ],
                producor: [
                    {required: true, message: '供应厂家必填！', trigger: 'change'}
                ],
                price: [
                    {
                        required: true,
                        pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/,
                        message: '只能输入不超过两位小数的数字',
                        trigger: 'blur'
                    }
                ],
                installPosition: [
                    {required: true, message: '备件类型必填！', trigger: 'change'}
                ],
                unit: [
                    {required: true, message: '单位必填！', trigger: 'change'}
                ],
                devTypeName: [
                    {required: true, message: '设备类型必填！', trigger: 'change'}
                ],
                reserve1: [
                    {required: true, message: '现场装机总量必填！', trigger: 'change'}
                ],
                planAbc: [
                    {required: true, message: '必须指定ABC类！', trigger: 'change'}
                ]
            },
            q: {
                Id: '',// 备件ID
                partCode: '', // 备件编码
                producor: '', // 厂家名称
                spec: '', // 规格
                erpCode: '', // 备件ERP编码
                partName: '',// 备件名称
                status: '', // 审批状态
                remark: '', // 备注
                createUserName: '' // 录入人
            },
            sourceList: enumsToList('SPARE_RESOURCES_TYPE'),
            statusList: enumsToList('APPVAL_STATUS'),
            typeList: enumsToList('SPARE_TYPE'),
            abcArray: enumsToListWithoutChange("ABC_TYPE"), // 备件ABC类
            partUnitList: [], // 备件单位列表，用于新增或修改备件时单位的下拉选择
            sparePartInstallPositionList: [], // 备件安装部位列表，用于新增或修改备件时安装部位的下拉选择
            sparePartOut: {
                delFlag: 1,
                remark: '',
                useDevId: '',
                useDevName: '',
                useDevCode: '',
                pickNoId: '',
                pickNo: '',
                repairNoId: '',
                repairNo: '',
                backNum: '',
                initNum: '',
                outNum: '',
                cargoLocation: '',
                partUnit: '',
                spec: '',
                name: '',
                partCode: '',
                outStoreId: '',
                outStore: '',
                useUnit: '',
                outDate: new Date(),
                outCode: '',
                id: '',
                checkDate: '',
                checkStatus: '1', //未审核
                checkUser: '',
                updateDate: '',
                updateUser: '',
                createUser: '',
                createDate: '',
                devTypeName: '',
                devType: ''
            },
            facType: '',
            auditTableColumns: [
                {
                    title: '环节名称',
                    key: 'workitemName',
                    width: 190
                },
                {
                    title: '审批状态',
                    key: 'state',
                    width: 100,
                    render: (h, params) => {
                        return sysEnums.OA_CHECK_FLAG[params.row.state];
                    }
                },
                {
                    title: '审批人',
                    key: 'approverName',
                    width: 90
                },
                {
                    title: '审批时间',
                    key: 'approveDate',
                    width: 160
                },
                {
                    title: '审批备注',
                    key: 'remark',
                    width: 150
                }
            ],
            auditTableData: [], // 审批table数据
            approveSparePartList: [], // 审核备件名称列表，审核窗口展示用
            rejectRemarkList: [], // 展示审批的备件中是否有已拒绝过得备件信息
            // 审核参数VO
            approveParam: {
                approveSparePartIdList: [],
                status: 1,
                remark: ''
            },
            spareSC: '' // 备件特殊字符
        }
    },
    created() {
        this.loadSpareSC();
    },
    methods: {
        //显示提示
        toggleVisibility: function () {
            const target = document.getElementById("target");
            if (target.style.visibility === "hidden") {
                target.style.opacity = "1";
                target.style.visibility = "visible";
            } else {
                target.style.opacity = "0";
                target.style.visibility = "hidden";
            }
        },
        //审核详情
        shviewOption: function (res) {
            let data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysoaprocess/queryAll',
                params: {busId: data.id, busType: 'SP'},
                type: 'POST',
                successCallback: function (res) {
                    vm.auditTableData = res.list;
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['700px', '480px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: $('#auditHistoryArea')
                    });
                }
            });
        },
        // 添加备件档案
        addEqu: function () {
            var id = getSelectedRow("#jqGrid");
            if (!id) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 备件档案',
                content: '../sys/ermsfile.html?moduleType=3&id=' + id
            })
        },
        loadSpareSC: function () {
            Ajax.request({
                url: '../sys/config/loadConfigValue?confKey=SPARE_SC',
                async: false,
                successCallback: resp => {
                    this.spareSC = resp.confValue;
                }
            });
        },
        getRoleList: function () {
            Ajax.request({
                url: '../sys/user/isPrivilege',
                async: false,
                successCallback: function (r) {
                    vm.isPrivilege = r.isPrivilege;
                }
            });
        },
        getSparePartUnit: function () {
            // 获取备件单位
            Ajax.request({
                url: '../sparepart/listUnit',
                async: false,
                successCallback: function (r) {
                    vm.partUnitList = r.sparePartUnits;
                }
            });
        },
        loadSparePartInstallPosition: function () {
            // 获取备件单位
            Ajax.request({
                url: '../sparepart/listCategory',
                async: false,
                successCallback: function (r) {
                    vm.sparePartInstallPositionList = r.list;
                }
            });
        },
        loadFacType: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择厂家',
                content: '../sys/factorytype_choose.html?type=1',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getFacType();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.sparePart.supplierId = res.id;
                        vm.sparePart.producor = res.faName;
                        vm.sparePart.producerCode = res.faCode;
                    }
                }
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.sparePart = {
                id: '',
                name: '',
                spec: '',
                delFlag: 1,
                // partCode: '',
                devCode: '',
                storeId: '',
                isChange: 0,
                isValid: 1,
                devTypeName: '',
                supplierId: '',
                producor: '',
                producerCode: '',
                devType: '',
                type: 0,
                safeNum: 0,
                initNum: 1,
                planAbc: '',
                reserve1: '', // 现场装机总量
                reserve2: '' // 备件图片保存
            };
            vm.isEditable = true;
            vm.getTreeShow();
            this.$nextTick(() => this.$refs.editTask.focus());
        },
        update: function (event) {
            let result = getSelectedRowData("#jqGrid");
            if (!result || result.id == null) {
                return;
            }
            let id = result.id;
            if (result.source == "ERP") {
                iview.Message.error("ERP库无权限操作");
                return;
            }
            // 非特权人员不允许修改审批过的数据
            if (vm.isPrivilege == 0 && result.status == 1) {
                alert("当前备件已审批通过，禁止更改！");
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getTreeShow();
            vm.getInfo(id);
            this.$nextTick(() => this.$refs.editTask.focus());
        },
        saveOrUpdate: function (event) {
            var url;
            if (vm.sparePart.id == (null || '')) {
                url = '../sparepart/save';
                vm.sparePart.stockNum = vm.sparePart.initNum;//新增 库存数量=初始数量
            } else {
                url = '../sparepart/update';
            }
            // 备件名称校验
            var flag = /^[a-zA-Z]+$/.test(vm.sparePart.name)
            if (flag) {
                alert('名称不能为全字母!');
                return
            }
            // 报废数校验
            if (vm.sparePart.scrapNum < 0) {
                alert('报废数量有误,请重新输入!');
                return;
            }
            // 如果有规格相同的
            Ajax.request({
                url: '../sparepart/isExists',
                params: {
                    'id': vm.sparePart.id,
                    'spec': vm.sparePart.spec
                },
                type: "POST",
                async: true,
                successCallback: function (r) {
                    if (r.rows) {
                        // 需要提示
                        confirm('已存在{ ' + r.rows + ' }规格与当前规格一致，是否继续添加？', function () {
                            Ajax.request({
                                url: url,
                                params: JSON.stringify(vm.sparePart),
                                type: "POST",
                                contentType: "application/json",
                                successCallback: function (r) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                }
                            });
                        });
                    } else {
                        Ajax.request({
                            url: url,
                            params: JSON.stringify(vm.sparePart),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                });
                            }
                        });
                    }
                }
            });
        },
        del: function (event) {
            // 获取待删除内容
            var result = getSelectedRowDatas("#jqGrid");
            if (!result || result.length == 0) {
                iview.Message.error("请选择备件记录");
                return;
            }
            // 构建删除数组
            var ids = [];
            for (var i = 0; i < result.length; i++) {
                // 非特权用户不可删除备件
                if (result[i].status == 1 && vm.isPrivilege == 0) {
                    alert("当前备件已审批通过，禁止更改！");
                    return;
                }
                ids.push(result[i].id);
            }
            if (ids.length == 0) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                //vm.sparePart.delFlag = 0;
                Ajax.request({
                    url: "../sparepart/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../sparepart/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.sparePart = r.sparePart;
                    vm.isEditable = r.isEditable;
                }
            });
        },
        reload: function (event) {
            const target = document.getElementById("target");
            target.style.opacity = "0";
            target.style.visibility = "hidden";
            vm.showList = true;
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'partCode': vm.q.partCode,
                    'producor': vm.q.producor,
                    'spec': vm.q.spec,
                    'erpCode': vm.q.erpCode,
                    'name': vm.q.partName,
                    'status': vm.q.status,
                    'remark': vm.q.remark,
                    'createUserName': vm.q.createUserName
                },
                page: page
            }).trigger("reloadGrid",[{page: 1}]);
            this.isEditable = true;
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                partCode: '',
                producor: '',
                spec: '',
                erpCode: '',
                partName: '',
                status: '',
                remark: '', // 备注
                createUserName: '' // 录入人
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            const target = document.getElementById("target");
            target.style.opacity = "0";
            target.style.visibility = "hidden";
            handleSubmitValidate(this, name, function () {
                if (vm.sparePart.planAbc == '4' || vm.sparePart.planAbc == '5') {
                    confirm('确定要ABC类为A-关键或C-消耗吗？', function () {
                        vm.saveOrUpdate()
                    });
                } else {
                    vm.saveOrUpdate()
                }
            });
        },
        handleReset: function (name) {
            const target = document.getElementById("target");
            target.style.opacity = "0";
            target.style.visibility = "hidden";
            handleResetForm(this, name);
        },
        //显示设备列表-所属设备编码
        getDeviceInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择设备',
                content: '../sys/deviceInfoSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getDeviceInfo();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.sparePart.devCode = res.devCode;
                        vm.sparePart.devName = res.devName;
                    }
                }
            })
        },
        //显示仓库列表
        getStoreHouse: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-institution"></i> 选择仓库',
                content: '../sys/storeHouseSelect.html?type=2',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getStoreHouse();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.sparePart.storeId = res.storeCode;
                    }
                }
            })
        },
        addDev: function (id, producor, devType) {
            //关联设备的厂商和类型
            openWindow({
                type: 2,
                title: '<i class="fa fa-plus-circle"></i> 添加设备',
                content: '../spare/sparepartdev.html?id=' + id +
                    '&producor=' + producor +
                    '&devType=' + devType
            })
        },
        addReplace: function (id, producor, devType) {
            //替换件关联设备的厂商和类型
            openWindow({
                type: 2,
                title: '<i class="fa fa-plus-circle"></i> 添加替换件',
                content: '../spare/sparedev.html?spareId=' + id +
                    '&producor=' + producor +
                    '&devType=' + devType
            })
        },
        //台账详情
        reportDetail: function (id) {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 台账详情',
                content: '../sys/reportDetail.html?id=' + id
            })
        },
        handleError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传格式正确的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 5M。'
            });
        },
        handleSuccess: function (res, file) {
            vm.sparePart.reserve2 = file.response.url;
            var url = vm.sparePart.reserve2;
            if (url) {
                this.$Loading.finish();
                iview.Message.success('文件上传成功');
            }
        },
        eyeFile: function (url) {
            if (url) {
                window.open(url);
            } else {
                alert('还未上传文件');
            }
        },
        getSparePartOut: function (id) {
            Ajax.request({
                url: "../sparepart/info/" + id,
                async: true,
                successCallback: function (res) {
                    vm.sparePartOut = res.sparePart;
                    vm.toolsPartOut.systemCode = res.sparePart.erpCode, //系统编码
                        vm.toolsPartOut.spec = res.sparePart.specs;//规格
                    vm.toolsPartOut.partUnit = res.sparePart.unit;//单位
                    vm.toolsPartOut.outStore = res.sparePart.workshopName;//出库仓库
                    vm.toolsPartOut.outStoreId = res.sparePart.workshop;//出库仓库
                    vm.toolsPartOut.cargoLocation = res.sparePart.cargoLocation;//货位
                    vm.toolsPartOut.partId = res.sparePart.belongTools;//所属工装
                }
            });

        },
        getInitNum: function (initNum) {
            if (initNum < 0) {
                alert('数量有误,请重新输入!');
                vm.sparePart.initNum = ''
                return;
            }
        },
        getSafeNum: function (safeNum) {
            if (safeNum < 0) {
                alert('数量有误,请重新输入!');
                vm.sparePart.safeNum = 0
                return;
            }
        },
        getStockNum: function (stockNum) {
            if (stockNum < 0) {
                alert('数量有误,请重新输入!');
                vm.sparePart.stockNum = ''
                return;
            }
        },
        getScrapNum: function (scrapNum) {
            if (scrapNum < 0) {
                alert('数量有误,请重新输入!');
                vm.sparePart.scrapNum = ''
                return;
            }
        },
        getReserve1: function (reserve1) {
            if (reserve1 < 0) {
                alert('数量有误,请重新输入!');
                vm.sparePart.reserve1 = '';
                return;
            }
        },
        apply: function () {
            // 校验是否选中记录
            var selectedSparePartList = getSelectedRowDatas('#jqGrid');
            if (!selectedSparePartList || selectedSparePartList.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }

            // 校验是否有上次审批不通过信息
            vm.rejectRemarkList = [];

            // 已审核的备件不允许重复审核
            vm.approveSparePartList = [];
            vm.approveParam = {
                approveSparePartIdList: [],
                status: '1',
                remark: ''
            }
            for (var i = 0; i < selectedSparePartList.length; i++) {
                if (selectedSparePartList[i].status == 1) {
                    alert('备件[' + selectedSparePartList[i].name + ']已通过审核，请取消选中！');
                    return;
                } else if (selectedSparePartList[i].status == 2 && selectedSparePartList[i].reserve3) {
                    vm.rejectRemarkList.push(selectedSparePartList[i].name + '[' + selectedSparePartList[i].partCode + ']' + ' : ' + selectedSparePartList[i].reserve3)
                }
                vm.approveSparePartList.push(selectedSparePartList[i].name + '[' + selectedSparePartList[i].partCode + ']');
                vm.approveParam.approveSparePartIdList.push(selectedSparePartList[i].id);
            }
            openWindow({
                title: "备件审核",
                area: ['600px', '450px'],
                content: jQuery("#apply"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: '../sparepart/Approval',
                        params: JSON.stringify(vm.approveParam),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            layer.close(index);
                            alert('审核完毕', function (index) {
                                vm.reload();
                            });
                        }
                    });
                }
            });
        },
        getTreeShow: function () {
            //加载分类树
            Ajax.request({
                url: '../devtype/listAll',
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                    var node = ztree.getNodeByParam("typeCode", vm.sparePart.devTypeName);
                    if (node) {
                        ztree.selectNode(node);
                        if (node.devTypeName) {
                            vm.sparePart.devTypeName = node.devTypeName;
                        } else {
                            vm.sparePart.devTypeName = '无';
                        }
                    } else {
                        node = ztree.getNodeByParam("id", "0");
                        ztree.selectNode(node);
                    }
                }
            });
        },
        devTypeShow: function () {
            var _this = this;
            openWindow({
                title: "选择设备类型",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var nodes = ztree.getSelectedNodes();
                    if (nodes && nodes.length > 0) {
                        var current = nodes[0];
                        if (current.level == 2) {
                            vm.sparePart.devType = current.typeCode;
                            vm.sparePart.devTypeName = current.typeName;
                            layer.close(index);
                        } else {
                            alert('请选择设备设备小类！');
                        }
                    } else {
                        alert('请选择一条记录！');
                    }
                }
            });
        },
        exportData: function () {
            var queryParam = [];
            if (vm.q.partCode) {
                queryParam.push('partCode=' + vm.q.partCode);
            }
            if (vm.q.producor) {
                queryParam.push('producor=' + vm.q.producor);
            }
            if (vm.q.spec !== '') {
                queryParam.push('spec=' + vm.q.spec);
            }
            if (vm.q.erpCode) {
                queryParam.push('erpCode=' + vm.q.erpCode);
            }
            if (vm.q.partName) {
                queryParam.push('partName=' + vm.q.partName);
            }
            if (vm.q.status) {
                queryParam.push('status=' + vm.q.status);
            }
            if (vm.q.remark) {
                queryParam.push('remark=' + vm.q.remark);
            }
            if (vm.q.createUserName) {
                queryParam.push('createUserName=' + vm.q.createUserName);
            }
            var paramUrl = '';
            if (queryParam.length > 0) {
                paramUrl = '?' + queryParam.join('&');
            }
            window.open('../sparepart/export' + paramUrl, '_blank');
        },
        handleBeforeUploadExcel: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleImportExcelSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.err
                })
            }
        },
        handleExcelFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleImportExcelError: function (err, file) {
            alert('导入失败');
        }
    },
    watch: {
        'sparePart.name': function () {
            this.$nextTick(function () {
            });
        }
    }
});
